#!/bin/sh
#
# This script implements a check for correct EC project
# C-language code formatting, and causes that check to happen on
# every commit.  Install to ".git/hooks/pre-commit".
#
# You can override the check by passing a --no-verify flag
# to git commit, or by running:
#   git config hooks.skipastylecheck true
#

astylecmd="tools/astyle-1.23-static --options=astyle.opt"

commitfiles=$(git diff --cached --name-only)

reformat_list=;

skipastylecheck=$(git config hooks.skipastylecheck)
if [ "$skipastylecheck" != "true" ]
then

	for f in $commitfiles
	do
		case $f in
		*.[chCH])
			# (file may not exist if we're committing a remove)
			if [ -e $f ]
			then
				# diff the output of astyle with the file itself
				if ! $astylecmd < $f | diff -q - $f >/dev/null
				then
					reformat_list="$reformat_list $f"
				fi
			fi
			;;
		esac
	done

	if [ "$reformat_list" ]
	then
		echo "Some files need reformatting.	 Run this command to fix them:"
		echo "(or use 'make format', which may affect more files)"
		echo
		echo $astylecmd $reformat_list
		echo
		echo "You may need to stage the reformatted files."
		echo "Disable this check with:	'git config hooks.skipastylecheck true'"
		exit 1
	fi
fi

exit 0
